<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/7
 * Time: 16:41
 */

namespace app\login\service;


use app\login\model\Popularize;

class RecordService
{
    # 根据username查找对应的数据
    public static function getFromName($name,$page,$limit,$model_str)
    {
        # 不能使用use直接动态生成模型， 只能使用下面的引入
        $classModel = 'app\\login\\model\\'.$model_str;
        $model = new $classModel;
        $result = $model->where('from','=',$name)
                    ->where('status', '<>', 0)
                    ->order(['add_time' => 'desc']);
        $count = $result->count();
        $data = $result->page($page,$limit)
            ->select();

        return [
            'count' => $count,
            'data' => $data,
            'code' => 0
        ];
    }
    # 按条件查找
    public static function getByCondition($name,$post,$model_str)
    {
        $page = $post['page'];
        $limit = $post['limit'];

        $filed = $post['field'];
        $time = $filed['time'];

        if(!strstr($time,'.')){
            $time_start = '';
            $time_end = '';
        }else {
            $date = explode('.', $filed['time']);
            $time_start = $date[0];
            $time_end = $date[1];
        }
        # 所有的字段
        $data = ['signData','status','phone','type','first','ip'];
        # 如果字段不存在则添加字段并设置值为空
        foreach ($data as $value){
            if(array_key_exists($value, $filed) == false){
                $filed[$value] = '';
            }
        }

        # 组装条件数组
        $arr = [
            'signData' => ['sign','=',$filed['signData']],
            'time' => ['add_time', 'between time', [$time_start, $time_end]],
            'status'=> ['status', '=', $filed['status']],
            'phone'=> ['phone', '=', $filed['phone']],
            'type'=> ['type', '=', $filed['type']],
            'first'=> ['first', '=', $filed['first']],
            'ip'=> ['ip', '=', $filed['ip']],
        ];
        # 组装where查询条件数组
        $where = [
            '0' => ['from','=',$name],
            '1' => ['status', '<>', 0]
        ];
        foreach ($filed as $key => $value){
            if($value == ''){
                unset($arr[$key]);
                continue;
            }
            array_push($where,$arr[$key]);
        }
        $classModel = 'app\\login\\model\\'.$model_str;
        $model = new $classModel;
        $page = new \Page\Page($model, $page, $limit, [], ['add_time'=>'desc'], $where);
        $result = $page->layuiPage();
        return $result;
    }
}